package org.example.common.configure.web.converter;

import com.google.common.collect.Maps;
import org.example.common.entity.IdEnum;
import org.springframework.core.convert.converter.Converter;

import java.util.Arrays;
import java.util.Map;
import java.util.Optional;

public class IdToEnumConverter<T extends IdEnum> implements Converter<String, T> {
    private final Map<String, T> idEnumMap = Maps.newHashMap();

    public IdToEnumConverter(Class<T> enumType) {
        Arrays.stream(enumType.getEnumConstants())
                .forEach(x -> {
                    idEnumMap.put(x.getId().toString(), x);
                });
    }

    @Override
    public T convert(String source) {
        return Optional.of(source)
                .map(idEnumMap::get)
                .orElseThrow(() -> new IllegalArgumentException("无效的枚举id"));
    }
}

